﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Linq;

namespace Supermarket.Dal
{
    public static class ShoppingCartDB
    {
        public static void AddItemForSale(Guid cartId, int productId, double quantity)
        {
            DataClassesSupermarketDataContext db = new DataClassesSupermarketDataContext();

            var item = (
                from c in db.ShoppingCarts
                where c.CartId == cartId && c.ProductId == productId && c.Supply == false
                select c).FirstOrDefault();

            if (item == null)
            {
                ShoppingCart cart = new ShoppingCart();
                cart.CartId = cartId;
                cart.ProductId = productId;
                cart.Quantity = quantity;
                cart.Supply = false;
                cart.DateCreated = DateTime.Now;

                db.ShoppingCarts.InsertOnSubmit(cart);
            }
            else
            {
                item.Quantity += quantity;
            }
            db.SubmitChanges();
        }


        public static List<object> GetCheckedProduct(Guid cartId)
        {
            DataClassesSupermarketDataContext db = new DataClassesSupermarketDataContext();
            var myCart =
                from cart in db.ShoppingCarts
                where cart.CartId == cartId && cart.Supply == false
                select new
                {
                    cart.Product.ProductName,
                    cart.Product.ProductPrice,
                    cart.Quantity,
                    ItemTotal = (decimal)cart.Quantity * cart.Product.ProductPrice
                };

            if (myCart.Count() > 0)
            {
                return myCart.ToList<object>(); ;
            }
            return null;
        }

        public static bool CheckOutSale(Guid CartId)
        {
            DataClassesSupermarketDataContext db = new DataClassesSupermarketDataContext();

            try
            {
                StringBuilder message = new StringBuilder();

                var myCart =
                    from cart in db.ShoppingCarts
                    where cart.CartId == CartId && cart.Supply == false
                    select cart;

                Sale sell = new Sale();
                sell.SaleOn = DateTime.Now;
                db.Sales.InsertOnSubmit(sell);
                db.SubmitChanges();

                decimal totalSum = 0m;

                foreach (var item in myCart)
                {
                    if (item.Quantity <= item.Product.InStock)
                    {
                        if (item.Quantity == item.Product.InStock)
                        {
                            item.Product.Enabled = false;
                        }
                        item.Product.InStock -= item.Quantity;
                        ProductsInSale saleDetail = new ProductsInSale();
                        saleDetail.SaleId = sell.SaleId;
                        saleDetail.ProductId = item.ProductId;
                        saleDetail.Quantity = item.Quantity;
                        saleDetail.ProductSellPrice = item.Product.ProductPrice;
                        db.ProductsInSales.InsertOnSubmit(saleDetail);
                        totalSum += saleDetail.ProductSellPrice * (decimal)saleDetail.Quantity;

                        var myItem = (
                            from c in db.ShoppingCarts
                            where c.CartId == item.CartId && c.ProductId == item.ProductId && c.Supply == false
                            select c).FirstOrDefault();
                        if (myItem != null)
                        {
                            db.ShoppingCarts.DeleteOnSubmit(myItem);
                        }
                    }
                    else
                    {
                        message.Append(string.Format("Няма достатъчно количество от \"{0}\". Налично - {1} {2}<br />",
                            item.Product.ProductName,
                            item.Product.InStock,
                            item.Product.Measure.MeasureCode));
                        db.ShoppingCarts.DeleteOnSubmit(item);
                    }
                }
                if (totalSum != 0)
                {
                    sell.TotalSum = totalSum;
                    var cashbox = (from cbox in db.CashBoxes select cbox).FirstOrDefault();
                    cashbox.Cash += totalSum;
                    db.SubmitChanges();
                }
                else
                {
                    var deleteSell = (
                        from s in db.Sales
                        where s.SaleId == sell.SaleId
                        select s).FirstOrDefault();
                    db.Sales.DeleteOnSubmit(deleteSell);
                    db.SubmitChanges();                    
                }
                if (message.Length > 0)
                {
                    throw new ArgumentOutOfRangeException(message.ToString());
                }
            }
            catch (ArgumentOutOfRangeException)
            {
                throw;
            }
            catch (Exception)
            {
                throw;
            }

            return true; //everything is OK
        }

        //CheckOutSupply

        public static void AddItemForSupply(Guid cartId, int productId, decimal productPrice, double quantity)
        {
            DataClassesSupermarketDataContext db = new DataClassesSupermarketDataContext();

            var item = (
                from c in db.ShoppingCarts
                where c.CartId == cartId && c.ProductId == productId && c.Supply == true
                select c).FirstOrDefault();

            if (item == null)
            {
                ShoppingCart cart = new ShoppingCart();
                cart.CartId = cartId;
                cart.ProductId = productId;
                cart.Quantity = quantity;
                cart.Supply = true;
                cart.DateCreated = DateTime.Now;
                cart.ProductSupplyPrice = productPrice;

                db.ShoppingCarts.InsertOnSubmit(cart);
            }
            else
            {
                item.Quantity += quantity;
            }
            db.SubmitChanges();
        }

        public static List<object> GetCheckedProductForSupply(Guid cartId)
        {
            DataClassesSupermarketDataContext db = new DataClassesSupermarketDataContext();
            var myCart =
                from cart in db.ShoppingCarts
                where cart.CartId == cartId && cart.Supply == true
                select new
                {
                    cart.Product.ProductName,
                    cart.ProductSupplyPrice,
                    cart.Quantity,
                    ItemTotal = (decimal)cart.Quantity * cart.ProductSupplyPrice
                };

            if (myCart.Count() > 0)
            {
                return myCart.ToList<object>(); ;
            }
            return null;
        }

        public static bool CheckOutSupply(Guid cartId)
        {
            DataClassesSupermarketDataContext db = new DataClassesSupermarketDataContext();

            try
            {
                StringBuilder message = new StringBuilder();
                decimal totalSum = 0m;

                var myCart =
                    from cart in db.ShoppingCarts
                    where cart.CartId == cartId && cart.Supply == true
                    select cart;
                
                totalSum = (decimal)myCart.Select(c => c.ProductSupplyPrice * (decimal)c.Quantity).Sum();
                var cashbox = (from cbox in db.CashBoxes select cbox).FirstOrDefault();
                
                if (totalSum > cashbox.Cash)
                {
                    message.Append("Няма наличната сума в касата!");
                    db.ShoppingCarts.DeleteAllOnSubmit(myCart);
                    db.SubmitChanges();
                    throw new ArgumentOutOfRangeException(message.ToString());
                }
                else
                {
                    Supply supply = new Supply();
                    supply.SupplyOn = DateTime.Now;
                    db.Supplies.InsertOnSubmit(supply);
                    db.SubmitChanges();

                    foreach (var item in myCart)
                    {
                        item.Product.Enabled = true;
                        item.Product.InStock += item.Quantity;
                        ProductsInSupply supplyDetail = new ProductsInSupply();
                        supplyDetail.SupplyId = supply.SupplyId;
                        supplyDetail.ProductId = item.ProductId;
                        supplyDetail.Quantity = item.Quantity;
                        supplyDetail.ProductSupplyPrice = (decimal)item.ProductSupplyPrice;
                        db.ProductsInSupplies.InsertOnSubmit(supplyDetail);
                        //totalSum += supplyDetail.ProductSupplyPrice * (decimal)supplyDetail.Quantity;

                        var myItem = (
                            from c in db.ShoppingCarts
                            where c.CartId == item.CartId && c.ProductId == item.ProductId && c.Supply == true
                            select c).FirstOrDefault();
                        if (myItem != null)
                        {
                            db.ShoppingCarts.DeleteOnSubmit(myItem);
                        }
                    }
                    cashbox.Cash -= totalSum;
                    supply.TotalSum = totalSum;
                    db.SubmitChanges();
                }
            }
            catch (ArgumentOutOfRangeException)
            {
                throw;
            }
            catch (Exception)
            {
                throw;
            }

            return true; //everything is OK
        }
    }
}
